<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入授权方或被授权方名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-dropdown size="mini" type="primary" @command="handleCommand">
          <el-button type="primary" size="mini">
            新建
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="0">一级授权</el-dropdown-item>
            <el-dropdown-item command="1">两级授权</el-dropdown-item>
            <el-dropdown-item command="2">三级授权</el-dropdown-item>
          </el-dropdown-menu>
          <!--          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPerm="['grant_add']"></el-button>-->
          <!--          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPerm="['grant_add']"></el-button>-->
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit"
          v-hasPerm="['grant_edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDel"
          v-hasPerm="['grant_del']"
        >删除
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery"/>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch"/>
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="tableDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="授权ID" align="center" prop="id"/>
      <el-table-column label="类型" width="80" align="center" prop="grantType">
        <template slot-scope="{row}">
          {{ status[row.grantType] || row.grantType}}
        </template>
      </el-table-column>
      <el-table-column label="一级授权方" align="center" prop="grant1.name">
        <template slot-scope="scope1">
          <el-popover trigger="hover" placement="top">
            <p>授权方: {{ scope1.row.grant1.name }}</p>
            <p>产品名称: {{ scope1.row.grant1.productName }}</p>
            <p>渠道名称: <el-tag :key="tag" v-for="tag in scope1.row.grant1.channelName" type="info">{{tag}}</el-tag></p>
            <p>开始时间: {{parseTime(scope1.row.startTime,'{y}-{m}-{d}')}}</p>
            <p>结束时间: {{parseTime(scope1.row.endTime,'{y}-{m}-{d}')}}</p>
            <p>授权书: <el-link v-for="file in JSON.parse(scope1.row.grant1.fileAuth)" :href="file.url" target="_blank"><el-tag size="mini">{{file.name}}</el-tag></el-link></p>
            <p>商标证书: <el-link v-for="file in JSON.parse(scope1.row.grant1.fileTrademark)" :href="file.url" target="_blank"><el-tag size="mini">{{file.name}}</el-tag></el-link></p>
            <div slot="reference" class="name-wrapper"><el-tag size="medium">{{ scope1.row.grant1.name }}</el-tag></div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="二级授权方" align="center" prop="grant2.name">
        <template slot-scope="scope2">
          <el-popover trigger="hover" placement="top" v-if="scope2.row.grant2!=null">
            <p>授权方: {{ scope2.row.grant2.name }}</p>
            <p>产品名称: {{ scope2.row.grant2.productName }}</p>
            <p>渠道名称: <el-tag :key="tag" v-for="tag in scope2.row.grant2.channelName" type="info">{{tag}}</el-tag></p>
            <p>开始时间: {{parseTime(scope2.row.startTime,'{y}-{m}-{d}')}}</p>
            <p>结束时间: {{parseTime(scope2.row.endTime,'{y}-{m}-{d}')}}</p>
            <p>授权书: <el-link v-for="file in JSON.parse(scope2.row.grant2.fileAuth)" :href="file.url" target="_blank"><el-tag size="mini">{{file.name}}</el-tag></el-link></p>
            <p>商标证书: <el-link v-for="file in JSON.parse(scope2.row.grant2.fileTrademark)" :href="file.url" target="_blank"><el-tag size="mini">{{file.name}}</el-tag></el-link></p>
            <div slot="reference" class="name-wrapper"><el-tag type="success" size="medium">{{ scope2.row.grant2.name }}</el-tag></div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="三级授权方" align="center" prop="grant3.name">
        <template slot-scope="scope3">
          <el-popover trigger="hover" placement="top" v-if="scope3.row.grant3!=null">
            <p>授权方: {{ scope3.row.grant3.name }}</p>
            <p>产品名称: {{ scope3.row.grant3.productName }}</p>
            <p>渠道名称: <el-tag :key="tag" v-for="tag in scope3.row.grant3.channelName" type="info">{{tag}}</el-tag></p>
            <p>开始时间: {{parseTime(scope3.row.startTime,'{y}-{m}-{d}')}}</p>
            <p>结束时间: {{parseTime(scope3.row.endTime,'{y}-{m}-{d}')}}</p>
            <p>授权书: <el-link v-for="file in JSON.parse(scope3.row.grant3.fileAuth)" :href="file.url" target="_blank"><el-tag size="mini">{{file.name}}</el-tag></el-link></p>
            <p>商标证书: <el-link v-for="file in JSON.parse(scope3.row.grant3.fileTrademark)" :href="file.url" target="_blank"><el-tag size="mini">{{file.name}}</el-tag></el-link></p>
            <div slot="reference" class="name-wrapper"><el-tag size="medium">{{ scope3.row.grant3.name }}</el-tag></div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="被授权方" align="center" prop="grant4.name" :show-overflow-tooltip="true">
        <template slot-scope="scope4">
          <el-popover trigger="hover" placement="top" v-if="scope4.row.grant4!=null">
            <p>被授权方: {{ scope4.row.grant4.name }}</p>
            <p>产品名称: {{ scope4.row.grant4.productName }}</p>
            <p>渠道名称: <el-tag :key="tag" v-for="tag in scope4.row.grant4.channelName" type="info">{{tag}}</el-tag></p>
            <p>开始时间: {{parseTime(scope4.row.startTime,'{y}-{m}-{d}')}}</p>
            <p>结束时间: {{parseTime(scope4.row.endTime,'{y}-{m}-{d}')}}</p>
            <p>授权书: <el-link v-for="file in JSON.parse(scope4.row.grant4.fileAuth)" :href="file.url" target="_blank"><el-tag size="mini">{{file.name}}</el-tag></el-link></p>
            <p>商标证书: <el-link v-for="file in JSON.parse(scope4.row.grant4.fileTrademark)" :href="file.url" target="_blank"><el-tag size="mini">{{file.name}}</el-tag></el-link></p>
            <div slot="reference" class="name-wrapper"><el-tag type="success" size="medium">{{ scope4.row.grant4.name }}</el-tag></div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" align="center" prop="grant4.productName" :show-overflow-tooltip="true"/>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime,'{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope1">
          <span>{{ parseTime(scope1.row.endTime,'{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPerm="['grant_edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDel(scope.row)"
            v-hasPerm="['grant_del']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加/修改授权对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px">
      <div>
        <el-row>
          <el-steps :active="active" finish-status="success">
            <el-step v-for="site in steps[grantType]" :title="site.title"></el-step>
          </el-steps>
        </el-row>
        <el-row></el-row>
        <el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="130px">
            <el-form-item label="">
            </el-form-item>
            <el-form-item :label="steps[grantType][active].title" prop="name">
              <el-input v-model="form.name" :placeholder="'请输入'+steps[grantType][active].title+'名称'" clearable/>
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" clearable/>
            </el-form-item>
            <el-form-item label="渠道名称" prop="channelName">
              <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)">
                {{tag}}
              </el-tag>
              <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
                        @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"/>
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加渠道</el-button>
            </el-form-item>
            <el-form-item label="授权时间" prop="dateRange">
              <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleDatePicker"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="授权书" prop="fileAuth">
              <el-upload class="upload-demo"
                         :headers="upload.headers"
                         :action="upload.url"
                         :disabled="upload.isUploading"
                         :on-preview="handlePreview" :on-remove="handleRemove1" :before-remove="beforeRemove" multiple
                         :on-success="handleFileSuccess1"
                         :limit="3" :on-exceed="handleExceed" :file-list="fileAuth">
                <el-button size="small" type="primary">点击上传</el-button>
                <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
            </el-form-item>
            <el-form-item label="商标证书" prop="fileTrademark">
              <el-upload
                class="upload-demo"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :on-preview="handlePreview" :on-remove="handleRemove2" :before-remove="beforeRemove" multiple :limit="3"
                :on-success="handleFileSuccess2"
                :on-exceed="handleExceed" :file-list="fileTrademark">
                <el-button size="small" type="primary">点击上传</el-button>
                <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-hasPerm="['grant_add','grant_edit']">下一步
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getAccessToken} from "@/utils/auth";
  import {
    listGrant,
    getGrant,
    getGrantByPId,
    delGrant,
    addGrant,
    editGrant
  } from "@/api/admin/grant";

  export default {
    name: "Grant",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 渠道表格数据
        tableDataList: [],
        // 日期范围
        dateRange: [],
        //品牌列表
        brandList: [],
        //渠道列表
        channelList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          current: 1,
          size: 10,
          name: undefined,
          key: undefined,
          isSys: undefined
        },
        // 显示搜索条件
        showSearch: true,
        // 表单参数
        form: {
          fileAuth: [],
          fileTrademark: []
        },
        // 表单校验
        rules: {
          name: [
            {required: true, message: '授权名称不能为空', trigger: 'blur'}
          ],
          productName: [
            {required: true, message: '产品名称不能为空', trigger: 'blur'}
          ],
          dateRange: [
            {required: false, message: '授权时间不能为空', trigger: 'change'}
          ]
        },
        pId: 0,
        active: 0,
        grantType: 0,
        fileAuth: [],
        fileTrademark: [],
        status: ['一级授权', '二级授权', '三级授权'],
        steps: [
          [{title: '品牌方'}, {title: '力瀚'}],
          [{title: '品牌方'}, {title: '代理/经销商'}, {title: '力瀚'}],
          [{title: '品牌方'}, {title: '代理'}, {title: '经销商'}, {title: '力瀚'}]
        ],
        dynamicTags: ['标签一', '标签二', '标签三'],
        inputVisible: false,
        inputValue: '',
        // 文件上传参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getAccessToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/aliyunUpload/photoUpload"
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      /** 查询渠道列表 */
      getList() {
        this.loading = true;
        listGrant(this.queryParams).then(response => {
            this.tableDataList = response.data;
            for (const _row of this.tableDataList) {
              _row.grant1.channelName = JSON.parse(_row.grant1.channelName || '[]');
              if (_row.grant2) {
                _row.grant2.channelName = JSON.parse(_row.grant2.channelName || '[]');
              }
              if (_row.grant3){
                _row.grant3.channelName = JSON.parse(_row.grant3.channelName || '[]');
              }
              if (_row.grant4){
                _row.grant4.channelName = JSON.parse(_row.grant4.channelName || '[]');
              }
            }
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      handleCommand(command) {
        this.grantType = command;
        this.handleAdd();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.getList();
      },
      // 表单重置
      reset() {
        this.fileAuth = [];
        this.fileTrademark = [];
        this.dateRange = [];
        this.form = {
          id: undefined,
          grantType: this.grantType,
          pId: undefined,
          name: undefined,
          remarks: undefined,
          fileAuth: [],
          fileTrademark: []
        };
        this.pId=0;
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.current = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加授权";
        this.active = 0;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleEdit(row) {
        this.reset();
        const id = row.id || this.ids
        this.loading = true;
        getGrant(id).then(response => {
            this.loading = false;
            this.form = response.data || {};
            this.dynamicTags=JSON.parse(this.form.channelName||'[]');
            this.grantType = this.form.grantType;
            this.pId = this.form.parentId || 0;
            this.form.fileAuth = JSON.parse(this.form.fileAuth);
            this.form.fileTrademark = JSON.parse(this.form.fileTrademark);
            this.fileAuth = this.form.fileAuth;
            this.fileTrademark = this.form.fileTrademark;
            this.dateRange = [this.form.startTime || '', this.form.endTime || ''];
            this.open = true;
            this.title = "修改授权";
          }
        );
      },
      /** 提交按钮 */
      submitForm: function () {
        this.loading=true;
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.startTime == null || this.form.endTime == null) {
              this.msgWarning("授权时间不能为空");
              this.loading=false;
              return;
            }
            console.log(this.form.fileAuth);
            console.log(this.form.fileTrademark);
            console.log(this.dynamicTags);
            this.form.grantType = this.grantType;
            this.form.level = this.active;
            this.form.fileAuth = JSON.stringify(this.form.fileAuth);
            this.form.fileTrademark = JSON.stringify(this.form.fileTrademark);
            this.form.channelName = JSON.stringify(this.dynamicTags);
            console.log(this.form);
            // return;
            this.loading = true;
            if (this.form.id != undefined) {
              editGrant(this.form).then(response => {
                this.loading = false;
                if (response.code === 0) {
                  this.msgSuccess("修改成功");
                  console.log(this.active);
                  console.log(this.steps[this.grantType].length);
                  if ((this.active + 1) >= this.steps[this.grantType].length) {
                    this.active = 0;
                    this.getList();
                    this.open = false;
                  } else {
                    this.active++;
                    this.loading = true;
                    this.pId = response.data.id;
                    let productName = response.data.productName;
                    getGrantByPId(this.pId).then(response => {
                      this.loading = false;
                      if (response.code === 0) {
                        if (response.data == null) {
                          this.reset();
                          this.form.parentId = this.pId;
                          this.form.productName = productName;
                          this.dynamicTags=[];
                        } else {
                          this.form = response.data;
                          this.pId = this.form.parentId;
                          this.form.fileAuth = JSON.parse(this.form.fileAuth);
                          this.form.fileTrademark = JSON.parse(this.form.fileTrademark);
                          this.dynamicTags=JSON.parse(this.form.channelName||'[]');
                          this.fileAuth = this.form.fileAuth;
                          this.fileTrademark = this.form.fileTrademark;
                          this.dateRange = [this.form.startTime || '', this.form.endTime || ''];
                        }
                      } else {
                        this.msgError(response.msg);
                      }
                    });
                  }
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              this.form.parentId = this.pId;
              addGrant(this.form).then(response => {
                this.loading = false;
                if (response.code === 0) {
                  this.dynamicTags=[];
                  this.msgSuccess("新增成功");
                  console.log(this.active);
                  console.log(this.steps[this.grantType].length);
                  if ((this.active + 1) >= this.steps[this.grantType].length) {
                    this.active = 0;
                    this.getList();
                    this.open = false;
                  } else {
                    console.log(response.data);
                    this.pId = response.data.id;
                    this.active++;
                    this.form.id = null;
                    this.form.name = null;
                    this.form.fileAuth = [];
                    this.form.fileTrademark = [];
                    this.fileAuth = this.form.fileAuth;
                    this.fileTrademark = this.form.fileTrademark;
                    this.form.parentId = this.pId;
                  }
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }else{
            this.loading=false;
          }
        });
      },
      /** 删除按钮操作 */
      handleDel(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除授权为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delGrant(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      handleDatePicker(data) {
        this.form.startTime = data[0]
        this.form.endTime = data[1]
      },
      handleRemove1(file, fileList) {
        this.form.fileAuth = this.packageFile(fileList);
      },
      handleRemove2(file, fileList) {
        this.form.fileTrademark = this.packageFile(fileList);
      },
      packageFile(fileList) {
        let a = [];
        for (const f of fileList) {
          a.push({name: f.response.data.name, url: f.response.data.url});
        }
        return a;
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      // 文件上传成功处理
      handleFileSuccess1(response, file, fileList) {
        this.form.fileAuth = this.packageFile(fileList);
      },
      handleFileSuccess2(response, file, fileList) {
        this.form.fileTrademark = this.packageFile(fileList);
      }
    }
  };
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
